package com.luoxiang.socialandroid.activity;

import static com.luoxiang.lib_common.common.Constants.MmkvConst.EXTRA;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.KEY;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.KEY_PHONE;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.luoxiang.socialandroid.R;
import com.luoxiang.socialandroid.adapter.SelectipAdapter;
import com.luoxiang.socialandroid.base.BaseActivity;
import com.luoxiang.socialandroid.bean.NumberBean;
import com.luoxiang.socialandroid.bean.SelectIpBean;
import com.luoxiang.socialandroid.bean.SendcodeBean;
import com.luoxiang.socialandroid.utils.AESUtil;
import com.luoxiang.socialandroid.utils.CustomClickListener;
import com.luoxiang.socialandroid.utils.MmkvUtil;
import com.luoxiang.socialandroid.utils.NetUtils;
import com.luoxiang.socialandroid.utils.NetUtils2;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class LoginbyCodeActivity extends BaseActivity {
    private TextView btn_getcode;
    private EditText edt_phone;
    private ImageView icon_back, imageOpenStats;
    private TextView tv_jiabaliu;
    private String edtPhone;
    public static LoginbyCodeActivity instance;
    private PopupWindow popupWindow;
    private RecyclerView recyclerView;
    private SelectipAdapter adapter;

    @Override
    protected void initListener() {

        icon_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        edt_phone.setInputType(InputType.TYPE_CLASS_PHONE);
        View view1 = LayoutInflater.from(LoginbyCodeActivity.this).inflate(R.layout.popup_selectid, null, false);
        popupWindow = new PopupWindow(view1, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        recyclerView = popupWindow.getContentView().findViewById(R.id.recySelectIp);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                imageOpenStats.setImageResource(R.mipmap.ic_login_open);
            }
        });

        tv_jiabaliu.setOnClickListener(new CustomClickListener() {
            @Override
            protected void onSingleClick() {
                imageOpenStats.setImageResource(R.mipmap.ic_login_close);
                popupWindow.showAsDropDown(edt_phone, 0, 0);
            }

            @Override
            protected void onFastClick() {

            }
        });

    }

    /**
     * EditText获取焦点并显示软键盘
     */
    public static void showSoftInputFromWindow(Activity activity, EditText editText) {
        editText.setFocusable(true);
        editText.setFocusableInTouchMode(true);
        editText.requestFocus();
        //显示软键盘
        activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
    }

    @Override
    protected void initLayout(Bundle savedInstanceState) {
        setContentView(R.layout.activity_loginby_code);
        setStatusBarTranslucent();
    }

    @Override
    protected void initView() {
        instance = this;
        btn_getcode = findViewById(R.id.btn_getcode);
        edt_phone = findViewById(R.id.edt_phone);
        icon_back = findViewById(R.id.icon_back);
        tv_jiabaliu = findViewById(R.id.tv_jiabaliu);
        imageOpenStats = findViewById(R.id.imageOpenStats);
        Edittextchange();
        showSoftInputFromWindow(LoginbyCodeActivity.this, edt_phone);
        getCountryMobilePrefixList(EXTRA);
    }

    /**
     * 获取验证码的方法
     *
     * @param phone
     * @param op
     */
    private void getLoginbycode(String phone, String op) {
        NetUtils2.getInstance().getApiService().getsendCode(phone, op, "")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<NumberBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        showLoading();
                    }

                    @Override
                    public void onNext(NumberBean numberBean) {
                        String data = numberBean.getData();
                        String decryptStr = null;
                        try {
                            decryptStr = AESUtil.aesDecryptString(data, KEY);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        LogUtils.i("decryptStr", decryptStr);
                        Gson gson = new Gson();
                        SendcodeBean sendcodeBean = gson.fromJson(decryptStr, SendcodeBean.class);
                        if (sendcodeBean != null) {
                            int code = sendcodeBean.getCode();
                            LogUtils.i("code", code);
                            if (code == 0) {
                                //跳转
                                ToastUtils.showShort(getString(R.string.mi_yanzhengmahuoquchenggong));
                                Intent intent = new Intent(LoginbyCodeActivity.this, EnterCodeActivity.class);
                                intent.putExtra("etphone", edtPhone);
                                startActivity(intent);
                            } else {
                                ToastUtils.showShort(sendcodeBean.getMsg());
                            }
                        }
                        clearLoading();

                    }

                    @Override
                    public void onError(Throwable e) {
                        clearLoading();
                    }

                    @Override
                    public void onComplete() {
                        clearLoading();
                    }
                });

    }

    private void Edittextchange() {
        edt_phone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                //代表没有输入
                if (edt_phone.length() < 7) {
                    btn_getcode.setBackground(getResources().getDrawable(R.drawable.shape_btn_getcode));
                    btn_getcode.setTextColor(Color.parseColor("#999999"));
                } else {
                    btn_getcode.setBackground(getResources().getDrawable(R.drawable.shape_send2code));
                    btn_getcode.setTextColor(Color.parseColor("#FFFFFF"));
                    btn_getcode.setOnClickListener(new CustomClickListener() {
                        @Override
                        protected void onSingleClick() {
                            getRequest();
                            edtPhone = tv_jiabaliu.getText().toString() + " " + LoginbyCodeActivity.this.edt_phone.getText().toString();
                            MmkvUtil.INSTANCE.encode(KEY_PHONE, edt_phone);
                            getLoginbycode(edtPhone, "login");
                        }

                        @Override
                        protected void onFastClick() {

                        }
                    });
                }
            }
        });
    }

    private void getCountryMobilePrefixList(String extra) {
        getRequest();
        NetUtils2.getInstance().getApiService().getCountryMobilePrefixList(extra)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<NumberBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onNext(NumberBean value) {
                        String data = value.getData();
                        String decryptStr = null;
                        try {
                            decryptStr = AESUtil.aesDecryptString(data, KEY);
                            com.luoxiang.lib_common.utils.LogUtils.i("decryptSelectid", decryptStr);
                            Gson gson = new Gson();
                            SelectIpBean selectIpBean = gson.fromJson(decryptStr, SelectIpBean.class);
                            if (selectIpBean.getCode() != 0) {
                                ToastUtils.showShort(selectIpBean.getMsg());
                            } else {
                                //在这里进行逻辑操作
                                adapter = new SelectipAdapter(selectIpBean.getData().getResult());
                                LinearLayoutManager linearLayoutManager = new LinearLayoutManager(LoginbyCodeActivity.this);
                                recyclerView.setLayoutManager(linearLayoutManager);
                                recyclerView.setAdapter(adapter);
                                adapter.setOnAddClickListener(new SelectipAdapter.OnAddClickListener() {
                                    @Override
                                    public void onItemClicks(String quhao) {
                                        //点击区号以后在这里处理
                                        tv_jiabaliu.setText("+" + quhao);
                                    }
                                });
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.i("erroroHttp", e.toString());
                    }

                    @Override
                    public void onComplete() {
                    }
                });
    }
}